﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DomainModel.Entities;
using Service.Abstract;

namespace WebUI.Controllers
{
    public class ProjectController : BaseController
    {
        private readonly IProjectService _projectService;
        private readonly ITaskService _taskService;
        private readonly IUserService _userService;

        public ProjectController(IUserService userService, ITaskService taskService, IProjectService projectService)
            : base(userService)
        {
            _projectService = projectService;
            _userService = userService;
            _taskService = taskService;
        }

        public ActionResult ProjectsList()
        {
            var projects = _projectService.GetAllByUserId(CurrentUser.UserId);
            return View("Project/ProjectList", projects);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddProject()
        {
            return PartialView("Project/AddProject");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddProject(Project project)
        {
            if(project.Name != string.Empty)
            {
                _projectService.Add(project, CurrentUser.UserId);
                return PartialView("Project/ProjectListSummary", project);
            }
            return null;
        }
        
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditProject(int listid)
        {
            return PartialView("Project/EditProject", _projectService.GetProjectById(listid));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditProject(Project project)
        {
            if(project.Name != string.Empty)
            {
                var model = _projectService.GetProjectById(project.Id);
                model.Name = project.Name;
                model.Description = project.Description;
                _projectService.Save(model, CurrentUser.UserId);
                return PartialView("Project/ProjectListSummary", model);
            }
            return null;
        }

        public void DeleteList(int listid)
        {
            var tasks = _taskService.GetTasksByProject(CurrentUser, listid).ToList();

            foreach (var task in tasks)
            {
                task.ProjectId = 0;
                _taskService.Save(task, CurrentUser.UserId);
            }
            _projectService.Delete(_projectService.GetProjectById(listid));
        }

        public ActionResult GetSettings(int listid)
        {
            return PartialView("Project/ListSettings", _projectService.GetProjectById(listid));
        }
    }
}
